package com.wavecoler.professor.bots;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.SortedMap;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;

import org.mortbay.log.Log;

import com.google.wave.api.AbstractRobot;
import com.google.wave.api.Blip;
import com.google.wave.api.Element;
import com.google.wave.api.ElementType;
import com.google.wave.api.FormElement;
import com.google.wave.api.event.FormButtonClickedEvent;
import com.google.wave.api.event.WaveletBlipCreatedEvent;
import com.google.wave.api.event.WaveletSelfAddedEvent;
import com.wavecoler.professor.dao.UserDAO;
import com.wavecoler.professor.objects.User;

@SuppressWarnings("serial")
public class BotUsers extends AbstractRobot {

	private static Logger LOG = Logger.getLogger(BotUsers.class.getName());
	private PersistenceManager pm;

	@Override
	protected String getRobotName() {
		return "Bot Users";
	}

	@Override
	protected String getRobotProfilePageUrl() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onWaveletSelfAdded(WaveletSelfAddedEvent event) {

		event.getWavelet().setTitle("Bot Users");

		Blip blip = event.getBlip();

		blip.append("\n");
		blip.append(new Element(ElementType.LABEL, createProperties("lblFName",
				"First Name:")));
		blip.append("\n");
		blip.append(new Element(ElementType.INPUT, createProperties("txtFName",
				"type first name here")));
		blip.append("\n");
		blip.append(new Element(ElementType.LABEL, createProperties("lblLName",
				"Last Name:")));
		blip.append("\n");
		blip.append(new Element(ElementType.INPUT, createProperties("txtLName",
				"type last name here")));
		blip.append("\n");
		blip.append(new Element(ElementType.LABEL, createProperties(
				"lblAccount", "Google Wave Account:")));
		blip.append("\n");
		blip.append(new Element(ElementType.INPUT, createProperties(
				"txtAccount", "type google wave account here")));
		blip.append("\n");
		blip.append(new FormElement(ElementType.CHECK, "isProfesor"));
		blip.append(new Element(ElementType.LABEL, createProperties("lblType",
				"Profesor?")));
		blip.append("\n");
		blip.append(new Element(ElementType.BUTTON, createProperties("btnAdd",
				"Add Participant")));

		/*
		 * User d = new User(); pm.makePersistent(d); pm.close();
		 */
	}

	@Override
	public void onWaveletBlipCreated(WaveletBlipCreatedEvent event) {
		// TODO Auto-generated method stub

	}

	private HashMap<String, String> createProperties(String name, String value) {
		HashMap<String, String> properties = new HashMap<String, String>();
		properties.put("name", name);
		properties.put("value", value);
		return properties;
	}

	@Override
	public void onFormButtonClicked(FormButtonClickedEvent e) {
		LOG.info("onFormButtonClicked");
		Blip blip = e.getBlip();
		SortedMap<Integer, Element> elements = e.getBlip().getElements();
		String button = e.getButtonName();
	
		User u = new User();
		u.setFirstName(getValue(elements.get(14)));
		
		u.setLastName(getValue(elements.get(18)));
		
		//valores temporales
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		String birthdate ="01/01/1970";
		Date birthdateP = null;
		try {
			birthdateP = sdf.parse(birthdate);
		} catch (ParseException e1) {
			LOG.info(e1.getMessage());
		}	
		u.setMiddleName("asd");
		u.setGender('F');
//		u.setDateOfBirth(birthdateP);
//		Descomentar quiza?
		
		
	    //continuar...
		String un = getValue(elements.get(22));
		u.setUserName(un);
		u.setActive(true);
		u.setOnline(false);
		if (getValue(elements.get(24)).equals("true"))
			u.setUserType("Professor");
		else
			u.setUserType("Student");
	
		UserDAO.insertUser(u);
		Blip reply = blip.reply();
		
		//C�digo para verificar si se insert� el usuario (s�lo quitar comentarios en caso de prueba)
		/* 
		User user = UserDAO.getUserById(u.getUserName());
		
		reply.append(user.getUserName());
		reply.append(user.getFirstName());
		reply.append(user.getMiddleName());
		reply.append(user.getLastName());
		reply.append(user.getDateOfBirth().toString());
		reply.append(user.getUserType());
		reply.append(user.getGender() + "");
		*/

		
		//C�digo para verificar el contenido de cada control.
		//Para obtener los �ndices de los controles, cambiar "elem.getProperty("value")" por "String.valueOf(key)"
		/*
		reply.append(e.getButtonName());
		SortedMap<Integer, Element> elements2 = e.getBlip().getElements();
		HashMap<String, String> responses = new HashMap<String, String>();

		for (Integer key : elements2.keySet()) {
			Element elem = elements2.get(key);
			if (elem.isFormElement()) {
				if (elem.getType() != ElementType.LABEL
						&& elem.getType() != ElementType.BUTTON) {
					responses.put(elem.getProperty("name"),
							elem.getProperty("value"));
				}
			}
		}

		// Check what was written
		for (String response : responses.keySet()) {
			reply.append("\nIn the field: '" + response + "' You typed: '"
					+ responses.get(response) + "'");
		}
		*/

	}

	private String getValue(Element fe) {
		Element elem = fe;
		String value = "";
		if (elem.isFormElement()) {
			if (elem.getType() != ElementType.LABEL
					&& elem.getType() != ElementType.BUTTON) {
				value = elem.getProperty("value");
			}
		}
		return value;
	}

}
